package cn.xorange.commons.datasource.configuration;

import cn.xorange.commons.data.build.myBatisPlus.SelectListPlus;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.injector.methods.*;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;

import java.util.*;

/**
 * @author : yangjian
 * date : 2024/12/10
 * description :
 */
public class CustomSqlInjector extends DefaultSqlInjector {

    @Override
    public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass){
        Class<?> modelClass = ReflectionKit.getSuperClassGenericType(mapperClass, Mapper.class, 0);
        if (modelClass != null) {
            String className = mapperClass.toString();
            Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
            if (!mapperRegistryCache.contains(className)) {

                TableInfo tableInfo = MyTableInfoHelper.initTableInfo(builderAssistant, modelClass);
                List<AbstractMethod> methodList = this.getMethodList(builderAssistant.getConfiguration(), mapperClass, tableInfo);

                if (CollectionUtils.isNotEmpty(methodList)) {
                    methodList.forEach((m) -> {
                        m.inject(builderAssistant, mapperClass, modelClass, tableInfo);
                    });
                } else {
                    this.logger.debug(className + ", No effective injection method was found.");
                }

                mapperRegistryCache.add(className);
            }
        }
    }
    @Override
    public List<AbstractMethod> getMethodList(Configuration configuration, Class<?> mapperClass, TableInfo tableInfo) {

        GlobalConfig.DbConfig dbConfig = GlobalConfigUtils.getDbConfig(configuration);
        List<AbstractMethod> methods = new ArrayList<>();
        methods.add(new Insert(dbConfig.isInsertIgnoreAutoIncrementColumn()));
        //methods.add(new SelectOne());
        methods.add(new SelectListPlus());
        return methods;
    }
}
